/*
*   Abricotine - Markdown Editor
*   Copyright (c) 2015 Thomas Brouard
*   Licensed under GNU-GPLv3 <http://www.gnu.org/licenses/gpl.html>
*/

var electron = require("electron"),
    app = electron.app,
    creator = require.main.require("./creator.js"),
    dialog = electron.dialog,
    session = electron.session,
    logger = require.main.require("./logger.js");

// Remote module
require('@electron/remote/main').initialize();

var abrApp = null,
    osxOpenFilePaths = [];

// Check app is single instance
// 鸿蒙平台兼容性处理：如果 requestSingleInstanceLock 不支持或失败，继续运行
function setupSingleInstanceLock() {
    try {
        if (app.requestSingleInstanceLock && typeof app.requestSingleInstanceLock === 'function') {
            var lockResult = app.requestSingleInstanceLock();
            if (!lockResult) {
                logger.warn("Single instance lock failed, continuing anyway");
                return false;
            }
            return true;
        } else {
            logger.debug("requestSingleInstanceLock not available on this platform");
            return false;
        }
    } catch (e) {
        logger.warn("Error requesting single instance lock: " + e.message);
        // 在鸿蒙平台上如果失败，继续运行而不是退出
        return false;
    }
}

setupSingleInstanceLock();

app.on("second-instance", (event, argv, cwd) => {
    try {
        process.chdir(cwd);
    } catch (e) {
        logger.warn("Failed to change directory: " + e.message);
    }
    if (abrApp == null) {
        logger.error("Error when trying to reach primary Abricotine instance");
        app.quit();
        return false;
    }
    abrApp.run(argv);
    return true;
});

// OSX open-file
app.on("open-file", function(event, path) {
    event.preventDefault();
    if (abrApp) {
        abrApp.open(path);
    } else {
        osxOpenFilePaths.push(path);
    }
});

// Quit app when all windows are closed
app.on("window-all-closed", function() {
    // 鸿蒙平台和 Linux/Windows 一样，关闭所有窗口时退出应用
    // macOS 平台保持窗口关闭后应用继续运行的行为
    if (process.platform != "darwin") {
        try {
            if (app.releaseSingleInstanceLock && typeof app.releaseSingleInstanceLock === 'function') {
                app.releaseSingleInstanceLock();
            }
        } catch (e) {
            logger.warn("Error releasing single instance lock: " + e.message);
        }
        app.quit();
    } else {
        if (abrApp) {
            abrApp.showMenu();
        }
    }
});

app.on("will-quit", function() {
    if (abrApp && typeof abrApp.emptyTmpHTML === 'function') {
        abrApp.emptyTmpHTML();
    }
});

app.on("ready", function () {
    logger.info("App ready, platform: " + process.platform);
    logger.info("Log file location: " + logger.getLogPath());
    
    // Install confirmation
    if (process.argv.indexOf("--squirrel-firstrun") !== -1) {
        try {
            var userChoice = dialog.showMessageBoxSync({
                title: "Abricotine setup",
                message: "Abricotine has been successfully installed.",
                type: "info",
                buttons: ["Exit", "Run Abricotine"],
                defaultId: 1
            });
            if (userChoice === 0) {
                app.exit(0);
            }
        } catch (e) {
            logger.warn("Error showing install confirmation: " + e.message);
        }
    }

    // Forbid unexpected Content-Types in received headers in default session (= editor) to protect against stegosploit (#254). Content types which don't start with "image/" will be deleted from header.
    function setupWebRequestFilter() {
        try {
            if (!session || !session.defaultSession || !session.defaultSession.webRequest) {
                logger.debug("webRequest API not available");
                return;
            }
            
            var filter = {
                // Allow devtool:// protocol
                urls: ["http://*/*", "https://*/*", "ws://*/*", "wss://*/*", "ftp://*/*"]
            };
            
            session.defaultSession.webRequest.onHeadersReceived(filter, function(details, callback) {
                try {
                    var responseHeaders = details.responseHeaders || {};
                    var contentTypeKey = Object.keys(responseHeaders).find(function(k) {
                        return k.toLowerCase() === "content-type";
                    });
                    
                    if (contentTypeKey) {
                        var contentType = responseHeaders[contentTypeKey] || [];
                        var newContentType = Array.isArray(contentType) ? contentType.filter(function(type) {
                            return /^image\//.test(type);
                        }) : [];
                        responseHeaders[contentTypeKey] = newContentType;
                    }
                    
                    callback({ cancel: false, responseHeaders: responseHeaders });
                } catch (e) {
                    logger.warn("Error processing webRequest headers: " + e.message);
                    callback({ cancel: false });
                }
            });
        } catch (e) {
            logger.warn("Error setting up webRequest filter: " + e.message);
        }
    }
    
    setupWebRequestFilter();

    // Load AbrApplication once app is ready
    try {
        var AbrApplication = require.main.require("./abr-application.js");

        // Reset config when --reset argument is used, otherwise ensure the config files exist
        var creatorFunc = process.argv.indexOf("--reset") !== -1 ? creator.reset : creator.create;
        creatorFunc()
            .then(creator.check)
            .then(function () {
                abrApp = new AbrApplication(osxOpenFilePaths);
                logger.info("AbrApplication initialized successfully");
            })
            .catch(function (err) {
                logger.error("Error initializing AbrApplication: " + (err.message || String(err)));
                // 即使初始化失败，也尝试创建一个窗口以便显示错误信息
                if (abrApp === null) {
                    logger.error("Failed to create application instance");
                }
            });
    } catch (e) {
        logger.error("Error loading AbrApplication: " + (e.message || String(e)));
    }
});
